<template>
    <div class="edit-user" ref="editAddModal">
        <a-modal 
            v-model:open="state.isShow"
            width="700px"
            wrapClassName="custom-modal"
            :bodyStyle="{height:'500px',overflowY:'overlay',overflowX:'hidden',paddingRight:'6px'}"
            :title="state.formState.id != undefined && state.formState.id > 0? '编辑账号':'添加账号'" 
            cancelText="取消"
            okText="确定"
            :getContainer="() => $refs.editAddModal"
            @ok="handleOk"
            @cancel="handleCancel"
        >
            <a-tabs v-model:activeKey="state.selectedTabName" >
                <a-tab-pane key="1" tab="基础信息">
                    <a-form
                        ref="formRef"
                        :model="state.formState"
                        name="basic-form"
                        autocomplete="off"
                        :label-col="{ span: 6 }"
                        :wrapper-col="{ span: 18 }"
                    >
                        <a-row >
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="账号名称"
                                    name="account"
                                    :rules="[{ required: true, message: '账号名称不能为空', trigger: 'blur' }]"
                                >
                                    <a-input v-model:value="state.formState.account" :disabled="state.formState.id > 0"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="昵称"
                                    name="nickName"
                                >
                                    <a-input v-model:value="state.formState.nickName" placeholder="昵称"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="手机号码"
                                    name="phone"
                                    :rules="[{ required: true, message: '手机号码不能为空', trigger: 'blur' }]"
                                >
                                    <a-input v-model:value="state.formState.phone"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="真实姓名"
                                    name="realName"
                                    :rules="[{ required: true, message: '真实姓名不能为空', trigger: 'blur' }]"
                                >
                                    <a-input v-model:value="state.formState.realName"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="账号类型"
                                    name="accountType"
                                    :rules="[{ required: true, message: '账号类型不能为空', trigger: 'blur' }]"
                                >
                                    <a-select
                                        v-model:value="state.formState.accountType"
                                        >
                                        <!-- 过滤超级管理员不可分配，系统管理员情况下，只能分配超管和系统管理权限以下 -->
                                        <template v-for="item in useMapDictList('AccountTypeEnum').filter((i:any)=>i.code != 'SuperAdmin' && (i.code == 'SysAdmin' ? AccountTypeEnum.NUMBER_999 === userInfoStore.state.userInfos.accountType: true))" :key="item.value">
                                            <a-select-option  :value="+item.value">{{ item.label }}</a-select-option>
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="邮箱"
                                    name="email"
                                >
                                    <a-input v-model:value="state.formState.email" placeholder="邮箱" />
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="排序"
                                    name="orderNo"
                                >
                                    <a-input-number class="w-full" v-model:value="state.formState.orderNo" placeholder="排序"/>
                                </a-form-item>
                            </a-col>
                            <a-divider>机构组织</a-divider>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="所属机构"
                                    name="orgId"
                                    :rules="[{ required: true, message: '所属机构不能为空', trigger: 'blur' }]"
                                >
                                    <a-cascader
                                        v-model:value="state.formState.orgId"
                                        :options="state.orgData"
                                        placeholder=""  
                                        :field-names="{ label: 'name', value: 'id', children: 'children' }"
                                        :changeOnSelect="true"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="职位"
                                    name="posId"
                                    :rules="[{ required: true, message: '职位名称不能为空', trigger: 'blur' }]"
                                >
                                    <a-select v-model:value="state.formState.posId">
                                        <template v-for="item in state.posData" :key="item.id">
                                            <a-select-option  :value="+item.id">{{ item.name }}</a-select-option>
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="工号"
                                    name="jobNum"
                                >
                                    <a-input v-model:value="state.formState.jobNum"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="域账号"
                                    name="domainAccount"
                                >
                                    <a-input v-model:value="state.formState.domainAccount"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="入职日期"
                                    name="joinDate"
                                >
                                    <a-date-picker v-model:value="state.formState.joinDate" class="w-full" valueFormat="YYYY/MM/DD"/>
                                </a-form-item>
                            </a-col>
                            <a-divider>附属机构</a-divider>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <div class="mb-3">
                                    <a-button class="mr-2" type="primary" @click="addExtOrgRow">增加附属机构</a-button>
                                    <span style="font-size: 12px; color: gray; padding-left: 5px">具有相应组织机构的数据权限</span>
                                </div>

                                <template v-if="state.formState.extOrgIdList && state.formState.extOrgIdList.length>0">
                                    <a-row v-for="(_,index) in state.formState.extOrgIdList" :key="_">
                                        <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                            <a-form-item
                                                :name="['extOrgIdList',index,'orgId']"
                                                :rules="[{ required: true, message: '所属机构不能为空', trigger: 'blur' }]"
                                            >
                                                <template #label>
                                                    <div class="flex items-center">
                                                        <a-button class="mr-2 flex justify-center items-center" danger  shape="circle" :icon="h(DeleteOutlined)" @click="deleteExtOrgRow(index)"/>
                                                        <span>机构</span>
                                                    </div>
                                                </template>
                                                <a-cascader
                                                    v-model:value="state.formState.extOrgIdList[index].orgId"
                                                    :options="props.orgData"
                                                    placeholder=""  
                                                    :field-names="{ label: 'name', value: 'id', children: 'children' }"
                                                    :changeOnSelect="true"
                                                />
                                            </a-form-item>
                                        </a-col>
                                        <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                            <a-form-item
                                                label="职位"
                                                :name="['extOrgIdList',index,'posId']"
                                                :rules="[{ required: true, message: '职位名称不能为空', trigger: 'blur' }]"
                                            >
                                                <a-select v-model:value="state.formState.extOrgIdList[index].posId">
                                                    <template v-for="item in state.posData" :key="item.id">
                                                        <a-select-option  :value="+item.id">{{ item.name }}</a-select-option>
                                                    </template>
                                                </a-select>
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                </template>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-tab-pane>
                <a-tab-pane key="2" tab="角色授权" force-render>
                    <a-transfer
                        v-model:target-keys="state.formState.roleIdList"
                        :data-source="state.roleData"
                        :titles="['未授权', '已授权']"
                        :render="(item:any) => item.name"
                        @change="handleTransferChange"
                    />
                </a-tab-pane>
                <a-tab-pane key="3" tab="档案信息">
                    <a-form
                        :model="state.formState"
                        name="dangan-form"
                        autocomplete="off"
                        :label-col="{ span: 6 }"
                        :wrapper-col="{ span: 18 }"
                    >
                        <a-row >
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="证件类型"
                                    name="cardType"
                                >
                                    <a-select
                                        v-model:value="state.formState.cardType"
                                    >
                                        <template v-for="item in useMapDictList('CardTypeEnum')" :key="item.value">
                                            <a-select-option  :value="+item.value">{{ item.label }}</a-select-option>
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="证件号码"
                                    name="idCardNum"
                                >
                                    <a-input v-model:value="state.formState.idCardNum"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="出生日期"
                                    name="birthday"
                                >
                                    <a-date-picker v-model:value="state.formState.birthday" valueFormat="YYYY/MM/DD" class="w-full"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="性别"
                                    name="sex"
                                >
                                    <a-select
                                        v-model:value="state.formState.sex"
                                        >
                                        <!-- 过滤超级管理员 -->
                                        <template v-for="item in useMapDictList('GenderEnum')" :key="item.value">
                                            <a-select-option  :value="+item.value">{{ item.label }}</a-select-option>
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="年龄"
                                    name="age"
                                >
                                    <a-input-number v-model:value="state.formState.age" :min="1" :max="150" class="w-full"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="民族"
                                    name="nation"
                                >
                                    <a-select
                                        v-model:value="state.formState.nation"
                                        >
                                        <!-- 过滤超级管理员 -->
                                        <template v-for="item in useMapDictList('NationEnum')" :key="item.value">
                                            <a-select-option  :value="+item.value">{{ item.label }}</a-select-option>
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <a-form-item
                                    label="地址"
                                    name="address"
                                    :label-col="{ span: 3 }"
                                    :wrapper-col="{ span: 21 }"
                                >
                                    <a-textarea :rows="2" v-model:value="state.formState.address"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="毕业学校"
                                    name="college"
                                >
                                    <a-input v-model:value="state.formState.college"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="文化程度"
                                    name="cultureLevel"
                                >
                                    <a-select
                                        v-model:value="state.formState.cultureLevel"
                                        >
                                        <!-- 过滤超级管理员 -->
                                        <template v-for="item in useMapDictList('CultureLevelEnum')" :key="item.value">
                                            <a-select-option  :value="+item.value">{{ item.label }}</a-select-option>
                                        </template>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="政治面貌"
                                    name="politicalOutlook"
                                >
                                    <a-input v-model:value="state.formState.politicalOutlook"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="办公电话"
                                    name="officePhone"
                                >
                                    <a-input v-model:value="state.formState.officePhone"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="紧急联系人"
                                    name="emergencyContact"
                                >
                                    <a-input v-model:value="state.formState.emergencyContact"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="联系人电话"
                                    name="emergencyPhone"
                                >
                                    <a-input v-model:value="state.formState.emergencyPhone"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <a-form-item
                                    label="联系人地址"
                                    name="emergencyAddress"
                                    :label-col="{ span: 3 }"
                                    :wrapper-col="{ span: 21 }"
                                >
                                    <a-textarea :rows="2" v-model:value="state.formState.emergencyAddress"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <a-form-item
                                    label="备注"
                                    name="remark"
                                    :label-col="{ span: 3 }"
                                    :wrapper-col="{ span: 21 }"
                                >
                                    <a-textarea :rows="2" v-model:value="state.formState.remark"/>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-tab-pane>
            </a-tabs>
        </a-modal>
    </div>
</template>

<script setup lang="ts" >
import { apiSysUserAddPost, apiSysUserOwnExtOrgListUserIdGet, apiSysUserOwnRoleListUserIdGet, apiSysUserUpdatePost } from '@/api/sys/apiUser';
import { useMapDictList } from '@/hooks';
import { reactive ,ref,onMounted,h} from 'vue';
import type { OrgDataType } from '../../org/type';
import { apiSysPosListGet } from '@/api/sys/sysPos';
import type { ResType } from '@/api/types';
import { apiSysRoleListGet } from '@/api/sys/sysRole';
import {DeleteOutlined} from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue';
import { useUserInfo } from '@/stores/userInfo';
import { AccountTypeEnum } from '@/enum';
import { emitter, findParentPath, showMsg } from '@/utils';
import { cloneDeep } from 'lodash';

const emits = defineEmits<{
    (e:"handleQuery"):void
}>()

const props = withDefaults(defineProps<{
    orgData: OrgDataType[]
}>(),{})

const userInfoStore = useUserInfo()


const formRef = ref<FormInstance>()
const editAddModal = ref()
const state = reactive({
    isShow:false,
    selectedTabName:'1',
    formState:{
    } as any,
    orgData:[] as OrgDataType[],
    posData:[] as any[],
    roleData:[] as any[],
    loading:false,
    orgId:[] as any[],
    submitData:{} as any,
})

const handleOk = async() => {
    await formRef.value?.validate()
    state.submitData = cloneDeep(state.formState)

    if (Array.isArray(state.submitData.orgId) && state.submitData.orgId.length > 0) {
        state.submitData.orgId = state.submitData.orgId[state.submitData.orgId.length - 1]
    }
    if(Array.isArray(state.submitData.extOrgIdList) && state.submitData.extOrgIdList.length > 0){
        state.submitData.extOrgIdList.forEach((e:any)=>{
            if (Array.isArray(e.orgId)) {
                e.orgId = e.orgId[e.orgId.length - 1]
            }
        })
    }
    if(Array.isArray(state.submitData.roleIdList) && state.submitData.roleIdList.length > 0){
        state.submitData.roleIdList = state.submitData.roleIdList.map((e:any)=> Number(e));
    }

    if(state.submitData.id != undefined && state.submitData.id > 0){
        await apiSysUserUpdatePost(state.submitData)
    }else{
        await apiSysUserAddPost(state.submitData)
    }
    showMsg("操作成功",'success')
    emits('handleQuery')
    handleCancel()
}



const handleOpen =async (row:any) => {
    // 确保多租户情况下，只能查看当前租户数据
    state.orgData = (row.tenantId ? props?.orgData.filter((e:any)=>e.tenantId === row.tenantId) : props.orgData) ?? []
    state.posData = (row.tenantId ? state?.posData.filter((e:any)=>e.tenantId === row.tenantId) : state.posData)?? []
    state.roleData = (row.tenantId? state?.roleData.filter((e:any)=>e.tenantId === row.tenantId) : state.roleData)?? []
    state.selectedTabName = '1'
    state.formState = {...JSON.parse(JSON.stringify(row))}
    // 处理级联数据格式
    state.formState.orgId = findParentPath(state.orgData,row.orgId)
    if (row.id != undefined) {
		var resRole =await apiSysUserOwnRoleListUserIdGet(row.id);
		state.formState.roleIdList = resRole.data.result ?? [];
        state.formState.roleIdList = state.formState.roleIdList.map((e:any)=>String(e));
        
		var resExtOrg = await apiSysUserOwnExtOrgListUserIdGet(row.id);
		state.formState.extOrgIdList = resExtOrg.data.result ?? [];
        state.formState.extOrgIdList.forEach((e:any)=>{
            e.orgId = findParentPath(state.orgData,e.orgId)
        })
    
	} else {
        state.formState.accountType = 777; // 默认普通账号类型
    }
    state.isShow = true
    formRef.value?.clearValidate()
}

const handleCancel = () => {
    state.isShow = false
    state.formState = {}
}

const addExtOrgRow = ()=>{
    if(!Array.isArray(state.formState.extOrgIdList)){
        state.formState.extOrgIdList = []
    }
    state.formState.extOrgIdList.push({})
}
const deleteExtOrgRow = (index:number)=>{
    state.formState.extOrgIdList.splice(index,1)
}

const handleTransferChange = (keys: string[], direction: string, moveKeys: string[])=>{

}


const initPosAndRoleList = async ()=>{
    state.loading = true
    var res = await apiSysPosListGet() as ResType<any[]>
    state.posData = res.data.result ?? []
    var res = await apiSysRoleListGet() as ResType<any[]>
    state.roleData = res.data.result ?? []
    // 穿梭器
    state.roleData = state.roleData.map(i=>{
        return {
            ...i,
            key:String(i.id)
        }
    })
    state.loading = false
}

onMounted(async()=>{
    await initPosAndRoleList()
    // 角色或则职位更新了就获取最新列表
    emitter.on('posOrRoleUpdate',initPosAndRoleList)
})

defineExpose({
    handleOpen
})
</script>

<style lang="scss" scoped>
:deep(.ant-modal-wrap) {
    .ant-tabs {
        .ant-tabs-nav {
            .ant-tabs-nav-list {
                width: 100%;
                display: flex !important;
                justify-content: space-around;
            }
        }
    }
} 
:deep(.ant-form-item){
    margin-bottom: 15px;
}

:deep(.ant-tabs){
    height:100%;
    .ant-tabs-content-holder{
        height:100%;
        &>div{
            height:100%;
        }
    }
}

:deep(.ant-transfer){
    height: 100%;
    display: flex;
    justify-content: space-between;
    .ant-transfer-list{
        width: 48%;
        height: 100%;
    }
    .ant-btn{
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
</style>